﻿using Furion;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace Pear.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            //配置JWT+Cookie混合授权
            services.AddJwt<JwtHandler>(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, b =>
            {
                b.LoginPath = "/User/Login";
                b.AccessDeniedPath = "/User/AccessDenied";
            });
            //分布式缓存-暂时用内存缓存代替
            services.AddDistributedMemoryCache();
            //配置跨域
            services.AddCorsAccessor();

            //配置请求审计日志
            services.AddMvcFilter<RequestAuditFilter>();

            //配置MVC
            var Mvc = services.AddControllersWithViews(options =>
            {
                options.EnableEndpointRouting = false;
            }).AddInjectWithUnifyResult().AddAppLocalization();
            //配置Furion的MVC及API
            //Mvc.AddInjectWithUnifyResult();
            //配置多语言
            //Mvc.AddAppLocalization();


        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error404");
                app.UseHsts();
            }
            //添加状态码拦截中间件
            app.UseUnifyResultStatusCodes();

            //跨域
            app.UseCorsAccessor();


            //多语言
            app.UseAppLocalization();

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            //记录请求日志
            app.UseSerilogRequestLogging();

            app.UseRouting();


            //授权
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject();

           
            //路由
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("areas", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}